﻿// 设置浏览器的UA
var spooferUserAgent = null;
var laserExtensionId = "nhgdinkjnnbljcoogpnopladkfnmbldo";
var isXML = function(doc) {
	return !!~doc.contentType.indexOf('xml');
}
chrome.runtime.sendMessage(laserExtensionId,{ message: 'getEnv'}, function (data) {
	if(!data || !data.isDebugger) return;
	if(isXML(document)) return;
	var a=document.createElement("script");
		a.type="text/javascript";
	if(data.app && data.version) {
		spooferUserAgent = window.navigator.userAgent +" "+data.app+"/"+data.version+' topsMock';
		document.addEventListener("beforeload", function(e){
			if(spooferUserAgent) {
				Object.defineProperty(window.navigator, 'userAgent', { get: function(){ return spooferUserAgent; } });
			}
		  },true);
		  if(spooferUserAgent) {
			  a.innerText+="Object.defineProperty(window.navigator, 'userAgent', { get: function(){ return '" + spooferUserAgent + "'; } });";

		  }
	}
	if(data.env) {
		// 设置接口的环境变量
		a.innerHTML +="window.__TOPS_ENV__="+JSON.stringify(data.env);
	}
	console.log(a);
	console.log(document.documentElement.nodeName);
	document.documentElement.insertBefore(a, document.documentElement.firstChild);
});


// 注意，必须设置了run_at=document_start 此段代码才会生效
document.addEventListener('DOMContentLoaded', function () {
	// 注入自定义JS
	injectCustomJs();

	// 给谷歌搜索结果的超链接增加 _target="blank"
	if (location.host == 'www.google.com.tw') {
		var objs = document.querySelectorAll('h3.r a');
		for (var i = 0; i < objs.length; i++) {
			objs[i].setAttribute('_target', 'blank');
		}
		console.log('已处理谷歌超链接！');
	}
});


// 向页面注入JS
function injectCustomJs(jsPath) {
	jsPath = jsPath || 'js/inject.js';
	var temp = document.createElement('script');
	temp.setAttribute('type', 'text/javascript');
	// 获得的地址类似：chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
	temp.src = chrome.extension.getURL(jsPath);
	temp.onload = function () {
		// 放在页面不好看，执行完后移除掉
		this.parentNode.removeChild(this);

	};
	temp.async = false;
	document.body.appendChild (temp);
}

// 接收来自后台的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
	if(isXML(document)) return;
	console.log('收到来自 ' + (sender.tab ? "content-script(" + sender.tab.url + ")" : "popup或者background") + ' 的消息：', request);
	if (request.cmd == 'update_font_size') {
		var ele = document.createElement('style');
		ele.innerHTML = `* {font-size: ${request.size}px !important;}`;
		document.head.appendChild(ele);
	}
	else {
		tip(JSON.stringify(request));
		sendResponse('我收到你的消息了：' + JSON.stringify(request));
	}
});

// 主动发送消息给后台
function sendMessageToBackground(message,cb) {
	chrome.runtime.sendMessage({ message: message}, function (response) {
		if(cb && cb instanceof Function) cb(response);
	});

}
// 监听长连接
chrome.runtime.onConnect.addListener(function (port) {
	console.log(port);
	if (port.name == 'test-connect') {
		port.onMessage.addListener(function (msg) {
			console.log('收到长连接消息：', msg);
			tip('收到长连接消息：' + JSON.stringify(msg));
			if (msg.question == '你是谁啊？') port.postMessage({ answer: '我是你爸！' });
		});
	}
});

// window.addEventListener("message", function (e) {
// 	console.log('收到消息：', e.data);
// 	if (e.data && e.data.cmd == 'invoke') {
// 		eval('(' + e.data.code + ')');
// 	}
// 	else if (e.data && e.data.cmd == 'message') {
// 		tip(e.data.data);
// 	}
// }, false);


function initCustomEventListen() {

	var hiddenDiv = document.getElementById('myCustomEventDiv');
	if (!hiddenDiv) {
		hiddenDiv = document.createElement('div');
		hiddenDiv.style.display = 'none';
		hiddenDiv.id = 'myCustomEventDiv';
		document.body.appendChild(hiddenDiv);
	}
	hiddenDiv.addEventListener('myCustomEvent', function () {
		var eventData = document.getElementById('myCustomEventDiv').innerText;
		tip('收到自定义事件：' + eventData);
	});
}

var tipCount = 0;
// 简单的消息通知
function tip(info) {
	if (isXML(document)) return;
	info = info || '';
	var ele = document.createElement('div');
	ele.className = 'chrome-plugin-simple-tip slideInLeft';
	ele.style.top = tipCount * 70 + 20 + 'px';
	ele.innerHTML = `<div>${info}</div>`;
	document.body.appendChild(ele);
	ele.classList.add('animated');
	tipCount++;
	setTimeout(() => {
		ele.style.top = '-100px';
		setTimeout(() => {
			ele.remove();
			tipCount--;
		}, 400);
	}, 3000);
}
